package com.zmx.piglearn.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log

class TestService : Service() {

    private val TAG = "### TestService"
    private var quit = false
    private val binder = MyBinder()
    private var count = 0
    inner class MyBinder : Binder() {
        fun getCount() = count
    }

    override fun onBind(intent: Intent?): IBinder? {
        Log.i(TAG, "onBind()")
        return binder
    }

    override fun onCreate() {
        Log.i(TAG, "onCreate()")
        super.onCreate()

        // 创建一个线程动态地修改 count 的值
        Thread {
            while (!quit) {
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                count++
            }
        }.start()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand()")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i(TAG, "onUnbind()")
        return super.onUnbind(intent)
    }

    override fun onRebind(intent: Intent?) {
        Log.i(TAG, "onRebind()")
        super.onRebind(intent)
    }

    override fun onDestroy() {
        Log.i(TAG, "onDestroy()")
        this.quit = true
        super.onDestroy()
    }
}